<?php

namespace App\Models\Member;

use App\Models\BaseModel;

class Grade extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'level', 'title',
        'describe', 'icon', 'type', 'bc_img', 
        'color_first', 'color_second', 'jf_num', 'recommend', 
        'created_at', 'updated_at'
    ];

    // 通过店铺ID 获取会员等级降序信息
    public function storeGrade($storeId, $orderby = 'desc')
    {
        return $this->where('store_id', $storeId)
        ->orderBy('level', $orderby)
        ->get()->toArray();
    }

    // 历史总积分 得出 对应的购物车底部TIP
    public function getTips($grades, $jf, $user)
    {
        // 如果是美康宝店铺，则升级条件全部按照历史获得积分来
        $level_str = $user['store_id'] != 21 ? ' 元':' 积分';
        $data = [];
        $cha = 0;
        $data['priceGrade'] = 0;
        $data['tipsText'] = '请选择商品~';
        foreach ($grades as $key => $val) {
            $recommend = json_decode($val['recommend'], 1);
            $numRecommend = User::where('left', '>', $user['left'])->where('right', '<', $user['right'])->where('grade', $recommend['grade'])->count();
            if ($key == 0 && $jf >= $val['jf_num'] && $numRecommend >= $recommend['num']) {
                $data['priceGrade'] = $val['level'];
                $data['tipsText'] = '当前享受 '.$val['title'].' 特惠价格~';
                break;
            } else {
                if ($jf >= $val['jf_num'] && $numRecommend >= $recommend['num']) {
                    $data['priceGrade'] = $val['level'];
                    $upJf = $grades[$key-1]['jf_num'];
                    $cha = $upJf - $jf;
                    // if ($cha == 0) {
                        // $data['tipsText'] = '当前享受 '.$grades[$key-1]['title'].' 特惠价格~';
                        // break;
                    // } else {
                        if ($cha <= 0) {
                            $data['tipsText'] = '还需推荐更多用户才能享受 '.$grades[$key-1]['title'].' 特惠价格';
                        } else { 
                            if ($user['store_id'] == 21) {
                                $data['tipsText'] = '还差 ' . $cha . $level_str . ' 可达到'.$grades[$key-1]['title'].'级别';
                            } else {
                                $data['tipsText'] = '还差 ' . $cha . $level_str . ' 可享受'.$grades[$key-1]['title'].'特惠价格';
                            }
                            
                        }
                        
                        break;
                    // }
                }
            }
        }
        return $data;
    }


}
